import { FormInstance } from 'ant-design-vue'
import { cloneDeep } from 'g6-fn'
import { reactive, ref } from 'vue'

/**
 * 模态框表单hook
 * @param state 表单数据
 * @returns
 * formRef
 * open
 * close
 * visible
 * modalTitle
 * formState
 * setFormState
 * resetForm
 * confirmLoading
 * changeConfirmLoading
 */
export const useModalForm = <T extends Object>(state: T) => {
  const modalTitle = ref('')
  const visible = ref(false)
  const confirmLoading = ref(false)
  const formState = reactive<T>(state)
  const cloneState = cloneDeep(state)
  const formRef = ref<FormInstance>()

  // 打开弹窗
  const open = (title: string, state?: T) => {
    modalTitle.value = title
    visible.value = true
    state && setFormState(state)
  }

  // 关闭弹窗
  const close = () => {
    resetForm()
    visible.value = false
  }

  // 设置表单数据
  const setFormState = (state: T) => {
    Object.assign(formState, state)
  }

  // 重置表单数据
  const resetForm = () => {
    Object.assign(formState, cloneState)
    formRef.value?.clearValidate()
  }

  // 改变确认按钮的loading状态
  const changeConfirmLoading = (bool: boolean) => {
    confirmLoading.value = bool
  }

  return {
    formRef,
    open,
    close,
    visible,
    modalTitle,
    formState,
    setFormState,
    resetForm,
    confirmLoading,
    changeConfirmLoading
  }
}
